<!--
设备概览页面
-->
<template>
  <rj-modal
    :visible="isVisible"
    width="780px"
    @cancel="closeModal"
    :footer="null"
  >
    <div slot="title">
      <rj-space :size="8">
        <span>{{ $t('exportPdf.reportManage') }}</span>
        <span
          ><a-tooltip
            placement="topLeft"
            :title="$t('exportPdf.tip1')"
            arrow-point-at-center
          >
            <icon-font type="ic-help" class="ic-help-tip" /> </a-tooltip
        ></span>
        <span>
          <icon-font
            type="ic-refresh"
            class="ic-help-tip"
            @click="getKingWordList"
        /></span>
      </rj-space>
    </div>
    <rj-table
      bordered
      :data-source="totalDataSource"
      :columns="totalColumns"
      :pagination="false"
    >
      <template slot="fname" slot-scope="text, record">
        <template v-if="record.fileid == 'now'">
          {{ record.fname }}
        </template>
        <rj-edittablecell
          v-else
          :title="$t('exportPdf.setFileName')"
          :placeholder="$t('exportPdf.setFileName')"
          :value="record.fname"
          :record="record"
          :checkRules="[
            {
              validator: checkAliasName,
            },
          ]"
          @change="valueChange(record, $event)"
        ></rj-edittablecell>
      </template>

      <template slot="mtime" slot-scope="text, record">
        <template v-if="record.fileid == 'now'">{{
          $t('exportPdf.maccCurrent')
        }}</template>
        <template v-else>{{
          new Date(text * 1000).Format('yyyy-MM-dd hh:mm')
        }}</template>
      </template>
      <template slot="operation" slot-scope="text, record">
        <template v-if="record.fileid == 'now'">
          <a-button @click="importKingWord">{{
            $t('exportPdf.import')
          }}</a-button>
        </template>
        <template v-else>
          <rj-space>
            <a href="javascript:;" @click="getCopyUrl(record)">{{
              $t('exportPdf.copyLink')
            }}</a>
            <a href="javascript:;" @click="onDelete(record)">{{
              $t('exportPdf.delete')
            }}</a>
          </rj-space></template
        >
      </template>
    </rj-table>
    <a-button
      :data-clipboard-text="shareUrl"
      id="copyBtn"
      @click="copyUrl($event)"
      style="border: none"
    ></a-button>
    <div style="text-align: right">
      <rj-space>
        <a-button @click="preData" :disbled="offset == 0">{{
          $t('exportPdf.previousPage')
        }}</a-button>
        <a-button @click="nextData">{{ $t('exportPdf.nextPage') }}</a-button>
      </rj-space>
    </div>
  </rj-modal>
</template>
<script>
import { mapState } from 'vuex';
import { requestHttp, maccApi } from '@utils/index';
import { RjModal, RjTable, RjEdittablecell } from '@components';
import clipboard from 'clipboard';
import { i18nRender } from '@/locales';
export default {
  name: 'deviceDetailDetailWin',
  props: {
    oldData: Object,
  },
  components: {
    'rj-modal': RjModal,
    'rj-table': RjTable,
    'rj-edittablecell': RjEdittablecell,
  },
  data() {
    return {
      totalColumns: [
        {
          title: i18nRender('exportPdf.name'),
          dataIndex: 'fname',
          key: 'fname',
          scopedSlots: { customRender: 'fname' },
        },
        {
          title: i18nRender('exportPdf.updateTime'),
          dataIndex: 'mtime',
          key: 'mtime',
          scopedSlots: { customRender: 'mtime' },
        },
        {
          title: i18nRender('exportPdf.oprate'),
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
          width: '180px',
          key: 'operation',
        },
      ],
      totalDataSource: [],
      offset: 0,
      shareUrl: '',
      isVisible: false,
    };
  },
  mounted() {},
  created() {},
  methods: {
    initView() {
      this.getKingWordList();
    },
    showModal() {
      this.isVisible = true;
      this.initView();
    },
    closeModal() {
      this.isVisible = false;
    },
    //获取文档列表
    async getKingWordList() {
      const data = await requestHttp({
        api: `${maccApi.DELIVERY_ONLINE_FILE_LIST.replace(
          '{groupId}',
          this.groupId
        )
          .replace('{offset}', this.offset)
          .replace('{count}', 10)}`,
        method: 'GET',
      });
      if (!data || 0 != data.code) {
        if (data.code == 5 && data.data) {
          this.$iframeMsg('REGISTER_COMTED', {
            eventName: 'DELIVERY_REPORT_WPS_AUTH_FINISH',
            comtedCallback: (comtedRet) => {
              this.kingnewtab && this.kingnewtab.close();
              if (comtedRet.code == 0) {
                this.$message.success('授权成功！');
                this.getKingWordList();
              } else {
                this.$message.error('授权失败！');
              }
            },
          });
          this.$message.info(this.$t('exportPdf.tip7'));
          this.kingnewtab = window.open(data.data, '_blank'); //
        } else {
          this.$message.error(data.msg);
        }
      } else {
        let list = data.data.list;

        if (list.length == 0 && this.offset > 0) {
          this.offset--;
          this.$message.info(this.$t('exportPdf.tip8'));
          return;
        }
        if (this.offset == 0) {
          list.unshift({
            fname:
              this.groupMap[this.groupId].name +
              this.$t('exportPdf.localDocument') +
              new Date().Format('yyyy-MM-dd'),
            fileid: 'now',
          });
        }
        this.totalDataSource = list;
      }
    },
    //获取url
    async getCopyUrl(record) {
      const data = await requestHttp({
        api: `${maccApi.DELIVERY_ONLINE_FILE_URL.replace(
          '{groupId}',
          this.groupId
        ).replace('{fileId}', record.fileid)}`,
        method: 'GET',
      });
      if (data && 0 == data.code) {
        this.shareUrl = data.data;

        this.$nextTick(() => {
          let copyBtn = document.getElementById('copyBtn');
          copyBtn.click();
        });
      }
    },
    copyUrl(event) {
      const clipboardObj = new clipboard('#copyBtn');
      //复制成功
      clipboardObj.on('success', () => {
        this.$message.success(this.$t('exportPdf.copySuccess'));
        clipboardObj.destroy();
      });
      //复制失败
      clipboardObj.on('error', () => {
        this.$message.error(this.$t('exportPdf.copyFail'));
        clipboardObj.destroy();
      });
      clipboardObj.onClick(event); //需要增加这行代码，否则要点击两次才复制生效（clipboard的坑）
    },
    //删除链接
    onDelete(record) {
      let self = this;
      RjModal.confirm({
        title: this.$t('exportPdf.delete'),
        content: () => this.$t('exportPdf.isDeleteDoc'),
        onOk() {
          self.setDeleteConfig(record);
        },
        onCancel() {},
      });
    },
    //下发删除配置
    async setDeleteConfig(record) {
      const data = await requestHttp({
        api: `${maccApi.DELIVERY_ONLINE_FILE_DELETE.replace(
          '{groupId}',
          this.groupId
        ).replace('{fileId}', record.fileid)}`,
        method: 'DELETE',
      });
      if (!data || 0 != data.code) {
        if (!data || 0 != data.code) {
          if (data.code == 5 && data.data) {
            this.$message.info(this.$t('exportPdf.tip7'));
            window.open(data.data, '_blank'); //let kingnewtab =
          } else {
            this.$message.error(data.msg);
          }
        }
      } else {
        this.offset = 0;
        this.getKingWordList();
      }
    },
    preData() {
      if (this.offset == 0) {
        this.$message.info(this.$t('exportPdf.tips4'));
        return;
      }
      this.offset--;
      this.getKingWordList();
    },
    nextData() {
      this.offset++;
      this.getKingWordList();
    },
    //导入新的文档
    importKingWord() {
      this.$emit('createKingWord', true);
    },
    /**
     * @description: 文件名称校验
     * @param {*} rule
     * @param {*} value
     * @param {*} callback
     * @return {*}
     */
    checkAliasName(rule, value, callback) {
      if (!/^[\w\u4E00-\u9FA5\-@#.()]+$/.test(value)) {
        callback(i18nRender('exportPdf.inputTip1'));
      } else if (value.length > 64) {
        callback(i18nRender('exportPdf.inputTiplen'));
      } else {
        callback();
      }
    },
    /**
     * 修订文件名
     */
    async valueChange(record, value) {
      let params = {
        groupId: this.groupId,
        fileId: record.fileid,
        newFileName: value,
      };
      const results = await requestHttp({
        api: `${maccApi.DELIVERY_ONLINE_FILE_RENAME}`,
        method: 'PUT',
        params: params,
      });
      if (results && results.code == 0) {
        this.$message.success(this.$t('exportPdf.settingSuccess'));
        const tableData = [...this.totalDataSource];
        const target = tableData.find((item) => item.fileid === record.fileid);
        if (target) {
          target.fname = value;
          this.totalDataSource = tableData;
        }
      } else {
        this.$message.error(results.msg);
      }
    },
  },
  watch: {},
  computed: {
    ...mapState('Group', ['groupId', 'groupMap']),
  },
};
</script>
<style lang="less" scoped></style>
